package com.argrace.smart.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.glide.GliderImageLoaderUtil;
import com.argrace.smart.model.LocalDb_QingJing_DeviceTable;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.utils;
import com.zhouyou.view.seekbar.SignSeekBar;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by argrace_dev_1 on 2018/2/12.
 */

public class DeviceControl_ChuangLianActivity extends BaseActivity {
    private TextView dakaichengdu;
    private SignSeekBar chuanglian;
    private ImageView left, stop, right;
    MineZigBeeDeviceListEntity bean;
    private ImageView img;
    private int type = ConstantConfigure.TYPE_CONTROL;
    private String name;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devicecontrol_chuanglian);
        init();
    }

    private void init() {
        bean = (MineZigBeeDeviceListEntity) getIntent().getSerializableExtra("deviceinfo");
        name = getIntent().getStringExtra("name");
        type = getIntent().getIntExtra("type", ConstantConfigure.TYPE_CONTROL);
        setView();
        setTitle(true, false, bean.getName());
        if (type == ConstantConfigure.TYPE_SETTING) {
            //进入设备修改保存状态界面
            showRight(true, R.mipmap.head_title_tick);
            setLeftandRightClickListeners(null, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String str_params = translateParams();
                    LocalDb_QingJing_DeviceTable entity = new LocalDb_QingJing_DeviceTable();
                    entity.setJson_params(str_params);
                    entity.updateAll("uuid = ? and LocalDb_DeviceTable_deviceId = ?", bean.getUuid(), name);
                    finish();
                }
            });
        } else {
            showRight(true, R.mipmap.icon_modify);
            //进入设备修改界面
            setLeftandRightClickListeners(null, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(DeviceControl_ChuangLianActivity.this, DeviceModifyActivity.class);
                    intent.putExtra("uuid", bean.getUuid());
                    intent.putExtra("model", bean.getModel());
                    startActivity(intent);
                }
            });
        }
        getDeviceDetailInfo();
    }

    private void setView() {
        img = (ImageView) findViewById(R.id.activity_devicecontrol_img);
        String imgurl = null;
        if (bean.getModel().equals(ConstantConfigure.MODEL_KAIHELIANDIANJI)) {
            imgurl = ConstantConfigure.IMGURL_KAIHELIANDIANJI_00041E40;
            dakaichengdu = (TextView) findViewById(R.id.activity_devicecontrol_chuanglian_text);
            chuanglian = (SignSeekBar) findViewById(R.id.activity_devicecontrol_chuanglian);
            left = (ImageView) findViewById(R.id.activity_devicecontrol_chuanglian_left);
            stop = (ImageView) findViewById(R.id.activity_devicecontrol_chuanglian_stop);
            right = (ImageView) findViewById(R.id.activity_devicecontrol_chuanglian_right);
            left.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendMsg("CurtainOperation", "1");
                }
            });
            right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendMsg("CurtainOperation", "0");
                }
            });
            stop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendMsg("CurtainOperation", "2");
                }
            });
            if (type == ConstantConfigure.TYPE_SETTING) {
                left.setVisibility(View.GONE);
                right.setVisibility(View.GONE);
                stop.setVisibility(View.GONE);
            }
            chuanglian.setOnProgressChangedListener(new SignSeekBar.OnProgressChangedListener() {
                @Override
                public void onProgressChanged(SignSeekBar signSeekBar, int progress, float progressFloat, boolean fromUser) {

                }

                @Override
                public void getProgressOnActionUp(SignSeekBar signSeekBar, int progress, float progressFloat) {
                    sendMsg("CurtainPosition", String.valueOf(progress));
                }

                @Override
                public void getProgressOnFinally(SignSeekBar signSeekBar, int progress, float progressFloat, boolean fromUser) {
//                    sendMsg("CurtainPosition", String.valueOf(progressFloat));
                }
            });

        }
        if (imgurl != null) {
            GliderImageLoaderUtil.load(this, imgurl, img);
        }
    }


    private void sendMsg(String key, String value) {
        if (type == ConstantConfigure.TYPE_SETTING) {
            return;
        }
        String method = "mtop.openalink.app.core.device.set.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        params.put("setParams", "{\"" + key + "\":\"" + value + "\"}");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Log.i("info", "发送消息成功" + transitoryResponse.data);
//                getDeviceDetailInfo();
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "发送消息失败");
            }
        });
    }

    //查询设备最新状态
    private void getDeviceDetailInfo() {
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);

                JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                fillData(obj, obj.getString("uuid"));
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    @Override
    protected void dorecieve(JSONObject obj) {
        super.dorecieve(obj);
        if (type == ConstantConfigure.TYPE_SETTING) {
            return;
        }
        if (obj == null || obj.getJSONObject("params") == null || obj.getJSONObject("params").getJSONObject("data") == null || obj.getJSONObject("params").getString("uuid") == null) {
            return;
        }
        fillData(obj.getJSONObject("params").getJSONObject("data"), obj.getJSONObject("params").getString("uuid"));
    }

    private void fillData(JSONObject obj, String uuid) {
        if (uuid == null || !uuid.equals(bean.getUuid())) {
            return;
        }
        if (bean.getModel().equals(ConstantConfigure.MODEL_KAIHELIANDIANJI)) {
            Key_ValueEntity bean4 = JSON.parseObject(obj.getString("CurtainPosition"), Key_ValueEntity.class);
            if (bean4 != null) {
                float progress_bean4 = (float) Double.parseDouble(bean4.getValue());
                chuanglian.setProgress(progress_bean4);
            }
        }
    }

    private String translateParams() {
        //0关闭，1开启
        Map<String, String> params = new HashMap<>();
        params.put("CurtainPosition", String.valueOf(chuanglian.getProgress()));
        return utils.getTheJson(params);
    }
}
